<template>
	<view class="mask flex-center">
		<view class="content botton-radius">
			<view class="content-top">
				<text class="content-top-text">{{ title }}</text>
				<image class="content-top" style="top: 0;" width="100%" height="100%" src="../../static/images/bg_top.png"></image>
			</view>
			<view class="content-header"></view>
			<view class="content-body">
				<view class="title">
					<text>{{ subTitle }}</text>
				</view>
				<view class="body">
					<scroll-view class="box-des-scroll" scroll-y="true">
						<text class="box-des">{{ contents }}</text>
					</scroll-view>
				</view>
				<view class="footer flex-center">
					<template v-if="!downloadSuccess">
						<view class="progress-box flex-column" v-if="downloading">
							<progress class="progress" border-radius="35" :percent="downLoadPercent"
								activeColor="#3DA7FF" show-info stroke-width="10" />
							<view class="download">
								<text>{{downLoadingText}}</text>
								<text>({{downloadedSize}}/{{packageFileSize}}M)</text>
							</view>
						</view>

						<button v-else class="content-button" plain @click="downloadPackage">
							{{downLoadBtnText}}
						</button>
					</template>
					<button v-else-if="downloadSuccess && !installed" class="content-button" plain @click="installPackage">
						{{$t('app.upgrade.downloadCompletedInstall')}}
					</button>

					<button v-if="installed" class="content-button" plain @click="restart">
						{{$t('app.upgrade.installCompletedRestart')}}
					</button>
				</view>
			</view>

			<image v-if="!is_mandatory" class="close-img" src="../../static/images/app_update_close.png" @click.stop="closeUpdate"></image>
		</view>
	</view>
</template>

<script>
	import { utilities } from '@/utils/common.js'
	
	const localFilePathKey = '__localFilePath__'
	let downloadTask = null;

	export default {
		// props: {
		// 	latestVersion: {
		// 		type: Object,
		// 		default() {
		// 			return {}
		// 		}
		// 	}
		// },
		data() {
			return {
				// 从之前下载安装
				installForBeforeFilePath: '',

				// 安装
				installed: false,

				// 下载
				downloadSuccess: false,
				downloading: false,

				downLoadPercent: 0,
				downloadedSize: 0,
				packageFileSize: 0,

				tempFilePath: '', // 要安装的本地包地址

				// 默认安装包信息
				title: this.$t('app.upgrade.newVersionFound'),
				subTitle: this.$t('app.upgrade.updateLog'),
				contents: '',
				is_mandatory: false,
				downLoadBtnText: this.$t('app.upgrade.downloadUpdatesNow'),
				downLoadingText: this.$t('app.upgrade.updatesDownloading')
			}
		},
		mounted() {
			this.init()
		},
		methods: {
			init() {
				this.latestVersion = uni.getStorageSync("latestVersion")
				this.contents = this.latestVersion.remark
				this.is_mandatory = this.latestVersion.versionAttr === 1 ? true : false
				this.version = this.latestVersion.appVersion
				this.url = this.latestVersion.downUrl
				
				this.checkLocalStoragePackage()
			},
			checkLocalStoragePackage() {
				// 如果已经有下载好的包，则直接提示安装
				const localFilePathRecord = uni.getStorageSync(localFilePathKey)
				if (localFilePathRecord) {
					const {
						version,
						savedFilePath,
						installed
					} = localFilePathRecord

					// 比对版本
					if (!installed && utilities.compareVersion(version, this.version) === 0) {
						this.downloadSuccess = true;
						this.installForBeforeFilePath = savedFilePath;
						this.tempFilePath = savedFilePath
					} else {
						// 如果保存的包版本小 或 已安装过，则直接删除
						this.deleteSavedFile(savedFilePath)
					}
				}
			},
			async closeUpdate() {
				if (this.downloading) {
					uni.showModal({
						title: this.$t('app.upgrade.cancelDownload'),
						cancelText: this.$t('common.field.no'),
						confirmText: this.$t('common.field.yes'),
						success: res => {
							if (res.confirm) {
								downloadTask && downloadTask.abort()
								this.$emit('close')
							}
						}
					});
					return;
				}
				this.$emit('close')
			},
			downloadPackage() {
				this.downloading = true;
				
				//下载包
				downloadTask = uni.downloadFile({
					url: this.url,
					success: res => {
						if (res.statusCode == 200) {
							this.downloadSuccess = true;
							this.tempFilePath = res.tempFilePath
							this.saveFile(this.tempFilePath, this.version)
							this.$emit('downloadSuccess')

							// 强制更新，直接安装
							if (this.is_mandatory) {
								this.installPackage();
							}
						}
					},
					complete: () => {
						this.downloading = false;

						this.downLoadPercent = 0
						this.downloadedSize = 0
						this.packageFileSize = 0

						downloadTask = null;
					}
				});

				downloadTask.onProgressUpdate(res => {
					this.downLoadPercent = res.progress;
					this.downloadedSize = (res.totalBytesWritten / Math.pow(1024, 2)).toFixed(2);
					this.packageFileSize = (res.totalBytesExpectedToWrite / Math.pow(1024, 2)).toFixed(2);
				});
			},
			installPackage() {
				// #ifdef APP-PLUS
				plus.runtime.install(this.tempFilePath, {
					force: false
				}, async res => {
					this.installed = true;

					const localFilePathRecord = uni.getStorageSync(localFilePathKey)
					uni.setStorageSync(localFilePathKey, {
						...localFilePathRecord,
						installed: true
					})
				}, async err => {
					// 如果是安装之前的包，安装失败后删除之前的包
					if (this.installForBeforeFilePath) {
						await this.deleteSavedFile(this.installForBeforeFilePath)
						this.installForBeforeFilePath = '';
					}

					// 安装失败需要重新下载安装包
					this.installed = false;

					uni.showModal({
						title: this.$t('app.upgrade.updateFailed'),
						content: err.message,
						showCancel: false
					});
				});

				this.$emit('close')
				// #endif
			},
			restart() {
				this.installed = false;
				// #ifdef APP-PLUS
				//更新完重启app
				plus.runtime.restart();
				// #endif
			},
			async saveFile(tempFilePath, version) {
				const [err, res] = await uni.saveFile({
					tempFilePath
				})
				if (err) {
					return;
				}
				uni.setStorageSync(localFilePathKey, {
					version,
					savedFilePath: res.savedFilePath
				})
			},
			deleteSavedFile(filePath) {
				uni.removeStorageSync(localFilePathKey)
				return uni.removeSavedFile({
					filePath
				})
			},
			jumpToAppStore() {
				plus.runtime.openURL(this.url);
			}
		}
	}
</script>

<style>
	page {
		background: transparent;
	}

	.flex-center {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
	}

	.mask {
		position: fixed;
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, .65);
	}

	.botton-radius {
		border-bottom-left-radius: 15px;
		border-bottom-right-radius: 15px;
	}

	.content {
		position: relative;
		top: 0;
		width: 300px;
		background-color: #fff;
		box-sizing: border-box;
		padding: 0 25px;
		font-family: Source Han Sans CN;
	}

	.text {
		/* #ifndef APP-NVUE */
		display: block;
		/* #endif */
		line-height: 200px;
		text-align: center;
		color: #FFFFFF;
	}

	.content-top {
		position: absolute;
		top: -95px;
		left: 0;
		width: 300px;
		height: 135px;
	}

	.content-top-text {
		font-size: 22px;
		font-weight: bold;
		color: #F8F8FA;
		position: absolute;
		top: 60px;
		left: 25px;
		z-index: 1;
	}

	.content-header {
		height: 35px;
	}

	.title {
		font-size: 16px;
		font-weight: bold;
		color: #3DA7FF;
		line-height: 38px;
	}

	.footer {
		height: 75px;
		display: flex;
		align-items: center;
		justify-content: space-around;
	}

	.box-des-scroll {
		box-sizing: border-box;
		padding: 0 20px;
		height: 100px;
		text-align: left;
	}

	.box-des {
		font-size: 14px;
		color: #000000;
		line-height: 25px;
	}

	.progress-box {
		width: 100%;
	}

	.progress {
		width: 90%;
		height: 20px;
		border-radius: 35px;
	}

	.download {
		width:100%;
		font-size: 14px;
		display: flex;
		justify-content: space-around;
	}

	.close-img {
		width: 35px;
		height: 35px;
		z-index: 1000;
		position: absolute;
		bottom: -60px;
		left: calc(50% - 35px / 2);
	}

	.content-button {
		text-align: center;
		flex: 1;
		font-size: 14px;
		font-weight: 400;
		color: #FFFFFF;
		border-radius: 20px;
		margin: 0 8px;

		height: 40px;
		line-height: 40px;

		background: linear-gradient(to right, #1785ff, #3DA7FF);
		
		border: none;
		color: #fff;
	}

	.flex-column {
		display: flex;
		flex-direction: column;
		align-items: center;
	}
</style>
